import { APICartList, APICartUpdate, APICartDelete } from './fetch.js';
import { getCookie } from './tools.js';


layui.use(['layer'], function () {
    var layer = layui.layer;


    var username = getCookie('login_user');

    if (!username) {
        $('.cart-none').show()
        $('.cartgoods').hide()
    } else {
        $('.thead').show()
        $('.jie').show()
    }

    var timer = null

    APICartList({
        username
    }).then(({ data }) => {
        //数组
        // console.log(data);
        var html = ''
        $.each(data, (index, { gname, price, count, img, id }) => {
            html += `
    <table>
    <tbody>
        <tr data-id="${id}">
            <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
            <td class="tutu"><a href="">
                    <img src="${img}" alt="">
                </a></td>
            <td>
                <div class="div">
                    <h4>${gname}</h4>
                    <span>规格：454g(1.0磅)</span>
                </div>
            </td>
            <td class="price">
                <p>¥${price}</p>
            </td>
            <td>
                <div class="numb">
                    <span class="jian">${count > 1 ? '-' : ''}</span>
                    <input class="num" type="text" value="${count}">
                    <span class="jia">+</span>
                </div>
            </td>
            <td>
                <p class="pp">¥${(price * count).toFixed(2)}</p>
            </td>
            <td class="td">
                <a class="aa" ><i></i></a>
            </td>
        </tr>
    </tbody>
</table>
        `
            $('.tbodybox').html(html);


        })
    })



    $(document).on('click', '.jia', function () {

        updateCount(this, 1);

        $(this).parents('tr').find('.jian').text('-');

    })
    $(document).on('click', '.jian', function () {
        if (!$(this).text()) return
        updateCount(this, -1);

    })
    //加减函数
    function updateCount(self, tag) {
        var id = $(self).parents('tr').attr('data-id')
        var count = $(self).parents('tr').find('.num').val() * 1;

        count += tag * 1

        if (count <= 1) {
            $(self).parents('tr').find('.jian').text('');
        }

        $(self).parents('tr').find('.num').val(count);

        var price = $(self).parents('tr').find('.price p').text().replace('¥', '') * 1;

        $(self).parents('tr').find('.pp').text(`¥${(count * price).toFixed(2)}`);

        clearTimeout(timer)
        timer = setTimeout(() => {
            APICartUpdate({
                id,
                count
            }).then(({ code }) => {
                if (code) {

                }
            })
        }, 500)
        getTotal()
    }


    //全选

    $('.lil4 input').change(function () {
        //被选中后下面的单选都选中
        $('.check-one').prop('checked', $(this).prop('checked'))
        getTotal()
    })
    //单选
    $(document).on('click', '.check-one', function () {
        // console.log($('.check-one:checked').length);
        checkAll()
    })
    //全选函数
    function checkAll() {
        if ($('.check-one').length === $('.check-one:checked').length) {
            $('.lil4 input').prop('checked', true)
        } else {
            $('.lil4 input').prop('checked', false)
        }
        getTotal()
    }
    //单个删除
    $(document).on('click', '.aa i', function () {
        APICartDelete({
            ids: JSON.stringify([$(this).parents('tr').attr('data-id')])           
        }).then(({ code,msg }) => {
            
            if (code) {
                $(this).parents('tr').remove();
                checkAll()
                layer.msg('删除成功')
            } else {
                layer.msg(msg)
            }
            panDuan()
        })
    })

    //全部删除
    $('.kong').click(function () {

        var ids = []

        $.each($('.check-one:checked'), function (index, item) {
            ids.push($(item).parents('tr').attr('data-id'))
        })
        APICartDelete({
            ids: JSON.stringify(ids)
            
        }).then(({ code,msg }) => {
            if (code) {
                $('.check-one:checked').parents('tr').remove();
                checkAll()
                layer.msg('删除成功');
            } else {
                layer.msg(msg)
            }

            panDuan()
            
        }) 
        
        


    })

    function panDuan() {
        if ($('.tbodybox tr').length === 0) {
            $('.cart-none').show()
            $('.cartgoods').hide()
        } else {
            $('.thead').show()
            $('.jie').show()
        }
    }





    //合计
    function getTotal() {
        //合计个数
        var count = 0;
        //合计金额
        var total = 0;
        
        $.each($('.check-one:checked'), function (index, item) {
            //取商品数量的值
            count += $(this).parents('tr').find('.num').val() * 1;
            //去商品总价的值
            total += $(this).parents('tr').find('.pp').text().replace('¥', '') * 1;
            // console.log(total);           
        });
        $('.p1 span').text(count);
        $('.p2 span').text(total.toFixed(2));
        $('.suan1 span').text(total.toFixed(2));
    }








})







